package com.atguigu.gmall.pay.api;

import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamsVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lsj
 * @create 2021-08-30 17:30
 */
@RequestMapping("/api/payment")
@RestController
public class PayController {

    @Autowired
    PayService payService;

    @Autowired
    OrderFeignClient orderFeignClient;

    /**
     * 去支付宝查询一个订单是否支付了
     * 1： 支付成功
     * 0:  其他状态
     * @param outTradeNo
     * @return
     */
    @GetMapping("/status/{outTradeNo}")
    public String queryOrderPayStatus(@PathVariable("outTradeNo") String outTradeNo) throws JsonProcessingException, AlipayApiException {
        Boolean b = payService.queryOrderStatus(outTradeNo);
        return b?"1":"0";
    }

    /**
     * 收到来自于前端页面，点击扫码支付。
     * @param orderId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/alipay/submit/{orderId}",produces = "text/html")
    public String payment(@PathVariable("orderId") Long orderId) throws Exception {
        // PayParamsVo: 支付宝所需的订单数据
        PayParamsVo paramsVo = new PayParamsVo();

        OrderInfo orderById = orderFeignClient.getOrderById(orderId);
        paramsVo.setTotal_amount(orderById.getTotalAmount().toString());
        paramsVo.setOut_trade_no(orderById.getOutTradeNo());

        paramsVo.setSubject(orderById.getConsignee()+"的订单");
        paramsVo.setBody(orderById.getOrderComment());
        Date expireTime = orderById.getExpireTime();
        //2016-12-31 10:05:01，支付宝的自动收单。支付宝订单过期时间就是我们数据库中保存的订单过期时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramsVo.setTime_expire(format.format(expireTime));
        //调用支付，返回支付页面
        String result = payService.payOrder(paramsVo);
        return result;
    }
}
